# -*- coding: utf-8 -*-
import json

from django.core import serializers
from django.http import HttpResponse

from TestModel.models import User


# 数据库查询操作
def select(request):
    result = User.objects.all()
    str = serializers.serialize("json", result)
    return HttpResponse(str)

def select1(request):
    result = User.objects.all()
    str = serializers.serialize("json", result)
    # 转换json并处理
    list = json.loads(str)
    arr = []
    for item in list:
        arr.append(item['fields'])
    print(arr)
    return HttpResponse("<p>" + json.dumps(arr) + "</p>")


def select3(request):
    result = User.objects.filter(id=11)
    str = serializers.serialize("json", result)
    # 转换json并处理
    list = json.loads(str)
    arr = []
    for item in list:
        arr.append(item['fields'])
    print(arr)
    return HttpResponse("<p>" + json.dumps(arr) + "</p>")

def select2(request):
    result = User.objects.filter().values('user_name')
    arr = list(result)
    # str = serializers.serialize("json", result)
    # # 转换json并处理
    # list = json.loads(str)
    # arr = []
    # for item in list:
    #     arr.append(item['fields'])
    # print(arr)
    return HttpResponse("<p>" + json.dumps(arr) + "</p>")

# 数据库添加操作
def insert(request):
    adduser = User(user_name='lax', user_sex='man', user_age='22', user_phone='1234567890', user_nick='coldchains', user_pwd='111')
    adduser.save()
    print(type(adduser))
    print(adduser)
    return HttpResponse("<p>数据添加成功！</p>")


# 数据库更新操作
def update(request):
    # 修改其中一个id=1的name字段，再save，相当于SQL中的UPDATE
    test1 = User.objects.get(id=1)
    test1.name = 'Google'
    test1.save()

    # 另外一种方式
    # User.objects.filter(id=1).update(name='Google')

    # 修改所有的列
    # User.objects.all().update(name='Google')

    return HttpResponse("<p>修改成功</p>")



# 数据库删除操作
def delete(request):
    # 删除id=1的数据
    test1 = User.objects.get(id=7)
    test1.delete()

    # 另外一种方式
    # User.objects.filter(id=1).delete()

    # 删除所有数据
    # User.objects.all().delete()

    return HttpResponse("<p>删除成功</p>")

